﻿using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System.Collections.Generic;
using evt;
using UnityEngine.SceneManagement;


public class ZJHSumUpCalculation : MonoBehaviour {

	// Use this for initialization
	public List<ZjhPlayer> playerList = null;
	private List<SumUpCell> list = new List<SumUpCell>();
	private Zjh.ResGameOverMsg msg;

	void Start () {
		ServerEventDispather.getInstance ().AddEventDispather (ServerEvent.UPDATE_ZJH_SUMUP,UpdateData);
		EventTriggerListener.Get (transform.GetChild (2).gameObject).onClick = Share;
		EventTriggerListener.Get (transform.GetChild (3).gameObject).onClick = JumpToMain;
	}

	private void UpdateData(object obj){
		msg = obj as Zjh.ResGameOverMsg;
	}

	private void Init(){
		ServerEventDispather.getInstance ().AddEventDispather (ServerEvent.HIDE_SETUP_VIEW, null);
		transform.GetChild (1).GetChild (0).GetChild (1).GetComponent<Text> ().text = "房间号:"+info.UserInfo.room.roomId.ToString();
		transform.GetChild (1).GetChild (0).GetChild (2).GetComponent<Text> ().text = "时间: "+System.DateTime.Now.Year +"年"+System.DateTime.Now.Month+"月"+System.DateTime.Now.Day +"日";

		GameObject pre = GameObject.Find ("SumUpPre");
		int x = 0;
		int y = 0;

		long winer = 0;
		long winerCret = 0;

		for(int s = 0 ; s < msg.record.items.Count ; s++ ){

			GameObject go = (GameObject)Instantiate (pre, transform);
			go.GetComponent<SumUpCell> ().PlayerId = msg.record.items [s].playerId;

			string nickName = "";
			for( int t = 0 ; t < playerList.Count ; t++ ){
				if( go.GetComponent<SumUpCell> ().PlayerId == playerList[t].Id ){
					go.GetComponent<SumUpCell> ().head = playerList [t].Head.sprite;
					nickName = playerList [t].P_name;
				}
			}

			go.GetComponent<SumUpCell> ().Mark = msg.record.items [s].cedit.ToString();
			go.GetComponent<SumUpCell> ().Name = nickName;
			go.GetComponent<SumUpCell> ().data = msg.record.items [s];

			go.transform.parent = transform;
			go.transform.localPosition = new Vector3 (-721 + s * 300, -77, 0);

			list.Add (go.GetComponent<SumUpCell> ());

			if(msg.record.items [s].cedit > winerCret){
				winerCret = msg.record.items [s].cedit;
				winer = msg.record.items [s].playerId;
			}


		}

		for( int n = 0 ; n < list.Count ; n++ ){
			if (list [n].PlayerId == winer) {
				list [n].IsBigWiner (true);
			} else {
				list [n].IsBigWiner (false);
			}
		}
	}

	public void Hide(){
		transform.localPosition = new Vector3(10000,0,0);
	}

	public void Show(){
		Init ();
		transform.localPosition = new Vector3(0,0,0);
	}

	private void JumpToMain(GameObject go){
		ServerEventDispather.getInstance ().removeAll ();
		info.UserInfo.UserData.roomId = 0;
		SceneManager.LoadScene (2);
	}

	private void Share(GameObject go){
		GameObject.Find("Main_ca").GetComponent<Demo> ().doWeiChatShareImageAndroid ();
	}
	
	// Update is called once per frame
	void Update () {
	
	}
}
